In [1]:
import numpy as np
In [2]:
def divergence(F):
""" compute the divergence of n-D scalar field `F` """
return reduce(np.add,np.gradient(F))
In [3]:
F = np.random.rand(100,100, 2)
In [4]:
F
Out[4]:
In [5]:
F.ndim
Out[5]:
In [6]:
F.shape
Out[6]:
In [7]:
from functools import reduce
In [8]:
def divergence_a(field):
"return the divergence of a n-D field"
return np.sum(np.gradient(field),axis=0)
In [9]:
timeit divergence_a(F)
In [10]:
d_a = divergence(F)
In [11]:
d_a.shape
Out[11]:
In [12]:
def divergence_b(F):
""" compute the divergence of n-D scalar field `F` """
return reduce(np.add,np.gradient(F))
In [13]:
timeit divergence_b(F)
In [14]:
d_b = divergence_b(F)
In [15]:
d_b.shape
Out[15]:
In [16]:
np.allclose(d_a, d_b)
Out[16]:
In [17]:
F = np.random.rand(100,100, 2)
In [18]:
def my_divergence(F):
dvx_dx = np.gradient(F[:, :, 0])[1]
dvy_dy = -(np.gradient(F[:, :, 1])[0])
return dvx_dx + dvy_dy
In [19]:
timeit my_divergence(F)
In [20]:
d_m = my_divergence(F)
In [21]:
F1, F2 = F[:, :, 0], F[:, :, 1]
In [22]:
def my_divergence_split(F1, F2):
dvx_dx = np.gradient(F1, axis=1)
dvy_dy = np.gradient(F2, axis=0)
return dvx_dx - dvy_dy
In [23]:
timeit my_divergence_split(F1, F2)
In [24]:
d_s = my_divergence_split(F1, F2)
In [25]:
np.allclose(d_m, d_s)
Out[25]: